<?php

class BookingsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','proxy','viewjson','additems'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Bookings;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                if(isset($_POST['Bookings']))
		{
                    print_r($_POST);
                    exit();
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Bookings']))
		{
			$model->attributes=$_POST['Bookings'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->booking_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */

        public function actionIndex()
	{       $model = new Bookings;
                
                if(isset($_POST['Bookings']))
                {   
                    $tonghanhkhach = $_POST['Bookings']['treem'] + $_POST['Bookings']['nguoilon'] + $_POST['Bookings']['sosinh'];
                    Yii::app()->user->setState('stt',$_POST['Bookings']['trangthai']);
                    Yii::app()->user->setState('diemdi',$_POST['Bookings']['diemdi']);
                    Yii::app()->user->setState('diemden',$_POST['Bookings']['diemden']);
                    Yii::app()->user->setState('ngaydi',$_POST['Bookings']['ngaydi']);
                    Yii::app()->user->setState('ngayve',$_POST['Bookings']['ngayve']);
                    Yii::app()->user->setState('treem',$_POST['Bookings']['treem']);
                    Yii::app()->user->setState('nguoilon',$_POST['Bookings']['nguoilon']);
                    Yii::app()->user->setState('sosinh',$_POST['Bookings']['sosinh']);
                    Yii::app()->user->setState('json', $_POST['Bookings']['storeJson']);
                    Yii::app()->user->setState('tonghanhkhach', $tonghanhkhach);
                    $this->redirect(array('viewjson'));
                    
                }
                
		$this->render('index',array('model'=>$model));
	}
        public function actionViewjson()
        {       
            
            if(isset($_POST['Bookings']))
            {
                
                Yii::app()->user->setState('gname',$_POST['Bookings']['gname']);
                Yii::app()->user->setState('gtime1',$_POST['Bookings']['gtime1']);
                Yii::app()->user->setState('gtime2',$_POST['Bookings']['gtime2']);
                Yii::app()->user->setState('gcost',$_POST['Bookings']['gcost']);
                Yii::app()->user->setState('ghangve',$_POST['Bookings']['ghangVe']);
                Yii::app()->user->setState('gcodeFlight',$_POST['Bookings']['gcodeFlight']);
                Yii::app()->user->setState('gcrypt',$_POST['Bookings']['gcrypt']);
                
                Yii::app()->user->setState('bname',$_POST['Bookings']['bname']);
                Yii::app()->user->setState('btime1',$_POST['Bookings']['btime1']);
                Yii::app()->user->setState('btime2',$_POST['Bookings']['btime2']);
                Yii::app()->user->setState('bcost',$_POST['Bookings']['bcost']);
                Yii::app()->user->setState('bhangve',$_POST['Bookings']['bhangVe']);
                Yii::app()->user->setState('bcodeFlight',$_POST['Bookings']['bcodeFlight']);
                Yii::app()->user->setState('bcrypt',$_POST['Bookings']['bcrypt']);
                
                 $this->redirect(array('additems'));
            }
            $this->render('viewjson');
        }
        public function actionAdditems(){
            $booking = new Bookings;
            if(isset($_POST['Bookings'])){
                $booking->name= $_POST['Bookings']['name'];
                $booking->danhxung= $_POST['Bookings']['quydanh'];
                $booking->phone= $_POST['Bookings']['phone'];
                $booking->email= $_POST['Bookings']['email'];
                $booking->city= $_POST['Bookings']['city'];
                $booking->address= $_POST['Bookings']['address'];
                $booking->country= $_POST['Bookings']['country'];
                $booking->payment= $_POST['Bookings']['payment'];
                $booking->numof_adults = Yii::app()->user->nguoilon;
                $booking->numof_childrens = Yii::app()->user->treem;
                $booking->numof_baby = Yii::app()->user->sosinh;
                $booking->booking_status = Yii::app()->user->stt;
                $booking->depart_airport_code = Yii::app()->user->diemdi;
                $booking->departing_date = Yii::app()->dateFormatter->format("y-MM-dd",Yii::app()->user->ngaydi) ;
                $booking->arive_airport_code = Yii::app()->user->diemden;
                $booking->arriving_date = Yii::app()->dateFormatter->format("y-MM-dd",Yii::app()->user->ngayve) ;
                $booking->cost1 = Yii::app()->user->gcost;
                $booking->cost2 = Yii::app()->user->bcost;
                
                if($booking->save())
                {

                    for ($i = 1; ; $i++) {
                        if ($i > Yii::app()->user->tonghanhkhach) {
                            break;
                        }
                        if(isset($_POST['booking_items'][$i]))
                        {
                            $item= new BookingItems;
                            $item->booking_id = $booking->booking_id;
                            $item->danhxung = $_POST['booking_items'][$i]['quydanh'];
                            $item->name = $_POST['booking_items'][$i]['name'];
                            $item->date_of_birth = $_POST['booking_items'][$i]['namsinh'].'-'.$_POST['booking_items'][$i]['thangsinh'].'-'.$_POST['booking_items'][$i]['ngaysinh'];
                            $item->flight_code = Yii::app()->user->gcodeFlight;
                            $item->ticket_class = Yii::app()->user->ghangve;
                            $item->flight_class = 'Lượt đi';
                            $item->baggage = $_POST['booking_items'][$i]['ghanhly'];
                            $item->ticket_price = Yii::app()->user->gcost;
                            $item->time1  = Yii::app()->user->gtime1;
                            $item->time2 = Yii::app()->user->gtime2;
                            $item->crypt = Yii::app()->user->gcrypt;
                            $item->save();
                            if(isset($_POST['booking_items'][$i]['bhanhly']))
                            {
                                $item= new BookingItems;
                                $item->booking_id = $booking->booking_id;
                                $item->danhxung = $_POST['booking_items'][$i]['quydanh'];
                                $item->name = $_POST['booking_items'][$i]['name'];
                                $item->date_of_birth = $_POST['booking_items'][$i]['namsinh'].'-'.$_POST['booking_items'][$i]['thangsinh'].'-'.$_POST['booking_items'][$i]['ngaysinh'];
                                $item->flight_code = Yii::app()->user->bcodeFlight;
                                $item->ticket_class = Yii::app()->user->bhangve;
                                $item->flight_class = 'Lượt về';
                                $item->baggage = $_POST['booking_items'][$i]['bhanhly'];
                                $item->ticket_price = Yii::app()->user->bcost;
                                $item->time1  = Yii::app()->user->btime1;
                                $item->time2 = Yii::app()->user->btime2;
                                $item->crypt = Yii::app()->user->bcrypt;
                                $item->save();
                            }
                        }
                    }
                    $this->redirect(array('viewjson'));
                }
            }
            $this->render('additems',array('model'=>$booking));
        }

        /**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Bookings('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Bookings']))
			$model->attributes=$_GET['Bookings'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Bookings the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Bookings::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
        public function actionProxy()
	{
		$url = $_POST['url'];
                unset($_POST['url']);

                $fields_string = "";

                foreach($_POST as $key=>$value) { 
                        $fields_string .= $key.'='.$value.'&'; 
                }
                $fields_string = rtrim($fields_string,'&');


                $ch = curl_init();
                ini_set('max_execution_time', 300);

                curl_setopt($ch,CURLOPT_URL,$url);
                curl_setopt($ch,CURLOPT_POST,count($_POST));
                curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);


                $result = curl_exec($ch);


                curl_close($ch);
	}
	/**
	 * Performs the AJAX validation.
	 * @param Bookings $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='bookings-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
       
}
